package cn.smbms.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	@RequestMapping(value="/userlist.html")
	public String getUserList(Model model,
							@RequestParam(value="queryname",required=false) String queryUserName,
							@RequestParam(value="queryUserRole",required=false) String queryUserRole,
							@RequestParam(value="pageIndex",required=false) String pageIndex){
		int _queryUserRole = 0;		
		List<User> userList = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
	
		if(queryUserName == null){
			queryUserName = "";
		}
		if(queryUserRole != null && !queryUserRole.equals("")){
			_queryUserRole = Integer.parseInt(queryUserRole);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			throw new RuntimeException("参数有误！");
    			//return "redirect:/user/syserror.html";
    			//response.sendRedirect("syserror.jsp");
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	int totalPageCount = pages.getTotalPageCount();
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist";
	}
	
	@RequestMapping(value="/useradd.html",method=RequestMethod.GET)
	public String addUser(){
		return "useradd";
	}
	
	@RequestMapping(value="/addsave.html",method=RequestMethod.POST)
	public String addUserSave(@Valid User user,BindingResult bindingResult,HttpServletRequest request
			,@RequestParam(value="attachs",required=false)MultipartFile[] attachs){
		
		if (bindingResult.hasErrors()) {
			return "useradd";
		}
		
		String idPicPath = null;
		String workPicPath = null;
		
		//文件上传
		//idPicPath = singleFileUpload(request, attach, idPicPath);
		
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
		
		String errorInof = null;
		
		for (int i = 0; i < attachs.length; i++) {
			MultipartFile attach = attachs[i];
			
			if (!attach.isEmpty()) {
				
				if (i==0) {  //证件照
					errorInof = "uploadFileError";
				} else { //工作证照片
					errorInof = "uploadWpError";
				}
				
				String oldFileName = attach.getOriginalFilename();//原文件名
				
				String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
		        
		        int filesize = 500000;
				
		        if(attach.getSize() >  filesize){//上传大小不得超过 500k
	            	request.setAttribute(errorInof, " * 上传大小不得超过 500k");
		        	return "error";
	            } else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
	            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
	            	
	            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";  
	               
	                File targetFile = new File(path, fileName);
	                
	                if(!targetFile.exists()){  
	                    targetFile.mkdirs();  
	                } 
	                
	                try {
						attach.transferTo(targetFile);
					}catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						request.setAttribute(errorInof, " * 上传失败！");
	                    return "error";
					}
	                
	                if (i==0) {
						idPicPath = path+File.separator+fileName;
					} else {
						workPicPath = path+File.separator+fileName;
					}
	                
	            }else{
	            	request.setAttribute(errorInof, " * 上传图片格式不正确");
	            	return "error";
	            }
		        
			}
		}
		
		//保存对象
		User loginUser =  (User) request.getSession().getAttribute(Constants.USER_SESSION);
		
		user.setCreatedBy(loginUser.getId());
		
		user.setIdPicPath(idPicPath);
		user.setWorkPicPath(workPicPath);
		
		boolean result = userService.add(user);
		
		if (result) {
			return "redirect:/user/userlist.html";
		}
		
		return "useradd";
	}

	private String singleFileUpload(HttpServletRequest request, MultipartFile attach, String idPicPath) {
		//处理文件上传
		if (!attach.isEmpty()) {
			//c:tomcat/smbms/statics/uploadfiles
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
			
			String oldFileName = attach.getOriginalFilename();//原文件名
			
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀  jpg
			
	        int filesize = 500000;
			
	        if(attach.getSize() >  filesize){//上传大小不得超过 500k
            	request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
	        	return "error";
            } else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
            	
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";  
                
            	//c:tomcat/smbms/statics/uploadfiles/325436543572345765_Personal.jpg
                File targetFile = new File(path, fileName);
                
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                } 
                
                try {
                	//上传
					attach.transferTo(targetFile);
				}catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					request.setAttribute("uploadFileError", " * 上传失败！");
                    return "error";
				}
                
                idPicPath = path+File.separator+fileName;
            }else{
            	request.setAttribute("uploadFileError", " * 上传图片格式不正确");
            	return "error";
            }
	        
		}
		return idPicPath;
	}
	
	@RequestMapping(value="/usermodify.html",method=RequestMethod.GET)
	public String getUserById(@RequestParam String uid,Model model){
		User user = userService.getUserById(uid);
		model.addAttribute(user);
		return "usermodify";
	}
	
	@RequestMapping(value="/usermodifysave.html",method=RequestMethod.POST)
	public String modifyUserSave(User user,HttpSession session){
		user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setModifyDate(new Date());
		if(userService.modify(user)){
			return "redirect:/user/userlist.html";
		}
		return "usermodify";
	}
	
	@RequestMapping(value="/view/{uid}",method=RequestMethod.GET)
	public String view(@PathVariable String uid,Model model){
		User user = userService.getUserById(uid);
		model.addAttribute(user);
		return "userview";
	}
	
	@RequestMapping(value="/ucexist.html")
	@ResponseBody
	public Object userCodeIsExit(@RequestParam String userCode){
		
		HashMap<String, String> resultMap = new HashMap<String, String>();
		
		if(StringUtils.isNullOrEmpty(userCode)){
			resultMap.put("userCode", "exist");
		}else{
			User user = userService.selectUserCodeExist(userCode);
			if(null != user)
				resultMap.put("userCode", "exist");
			else
				resultMap.put("userCode", "noexist");
		}
		//[{"userCode":"exist"},{},{}]
		return JSONArray.toJSONString(resultMap);
	}
	
	@RequestMapping(value="/view",method=RequestMethod.GET)
	@ResponseBody
	public User view(@RequestParam String id){
		User user = new User();
		try {
			user = userService.getUserById(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
}
